import { MessagePlugin } from 'tdesign-vue-next';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style
import STYLE_CONFIG from '@/config/style';

import { getPermissionStore, getUserStore } from '@/store';
import router from '@/router';

const permissionStore = getPermissionStore();
const userStore = getUserStore();

NProgress.configure({ showSpinner: false });

const { whiteListRouters } = permissionStore;

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  if (to.meta && to.meta.title) {
    document.title = `${to.meta.title} - ${STYLE_CONFIG.title}`;
  }
  const { token } = userStore;
  if (token) {
    if (to.path === '/login') {
      next(`/`);
      return;
    }
    const { permissions } = userStore;
    if (permissions && permissions.length > 0) {
      next();
    } else {
      try {
        await userStore.getUserInfo();
        const { permissions } = userStore;
        if (!permissions || !permissions.length) {
          MessagePlugin.error('账号未分配权限').then(() => {
            userStore.logout();
            permissionStore.restore();
          });
          next(`/login?redirect=${to.path}`);
          NProgress.done();
          return;
        }
        await permissionStore.initRoutes(permissions);
        if (router.hasRoute(to.name)) {
          next();
        } else {
          next(`/`);
        }
      } catch (error) {
        console.log('err', error);
        MessagePlugin.error('账号异常').then(() => {
          userStore.logout();
          permissionStore.restore();
          next(`/login?redirect=${to.path}`);
        });
      }
    }
  } else {
    /* white list router */
    if (whiteListRouters.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login?redirect=${to.path}`);
    }
    NProgress.done();
  }
});

router.afterEach(() => {
  NProgress.done();
});
